
package com.compuvest.admin.update.v1

import org.apache.commons.fileupload.FileItem
import org.apache.commons.fileupload.FileUploadException
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload

import javax.naming.InitialContext

import javax.servlet.ServletConfig

import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.annotation.WebServlet;

import groovy.sql.Sql

@WebServlet("/transactions/UpdateTracking")
class TrackingService extends HttpServlet {

    def sql

    def void init(ServletConfig config) {
	super.init(config)

        def ds = new InitialContext().lookup("jdbc/mysql")
        sql = new Sql(ds)

        sql.eachRow('select VERSION()') { row ->
            println ">>>>TrackingService() version=${row[0]}"
        }
    }


    def void processRequest(request, response) {

        def startEvent = System.currentTimeMillis()

        if(ServletFileUpload.isMultipartContent(request)) {

            def diskFileItemFactory = new DiskFileItemFactory()
            diskFileItemFactory.setSizeThreshold(1024) // the unit is bytes in memory

            def servletFileUpload = new ServletFileUpload(diskFileItemFactory)
            servletFileUpload.setSizeMax(1024) // the unit is bytes

            def fileItemsList = servletFileUpload.parseRequest(request)
            //println ">>>fileItemsList=[${fileItemsList.toString()}]"

            def ponumber, tracking, result = 'Error'
            fileItemsList.each { field ->
                if(field.fieldName == 'PONumber') {
                    ponumber = field.getString()
                }
                else if(field.fieldName == 'Tracking') {
                    tracking = field.getString()
                }
            }
            //println "[ponumber=${ponumber} : tracking=${tracking}"

            if(ponumber && tracking && ponumber.length() < 16) {
                sql.call("{ call sklad.updateTracking(?,?) }", [ponumber, tracking]) // orderNumber, trackingNumber
                result = 'Ok'
            }

        }

        response.setContentType("text/xml;charset=UTF-8")
        def out = response.getWriter()
        out.print(
            """<?xml version='1.0' encoding='UTF-8'?>
            <status>
            <time>${System.currentTimeMillis() - startEvent}ms.</time>
            <code>1</code>
            <message>Ok</message>
            </status>"""
        )
    }


    def void doGet(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    def void doPost(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    String getServletInfo() {
        return "TrackingService"
    }
}

